package com.example.secondhandspringboot.utils;


import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

public class IpUtil {

    //去百度地图开放平台申请ak
    private static final String ak = "";
    private static final OkHttpClient client = new OkHttpClient();


    /*
    将ip转换为地理信息
    */
    public static String ipReverse(String ip){
        String url = "http://api.map.baidu.com/location/ip?ak="+ak+"&ip="+ip;
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("ip转换发生错误:" + response);
            Gson gson = new Gson();
            JsonObject jsonObject;
            if (response.body() != null) {
                jsonObject = gson.fromJson(response.body().string(), JsonObject.class);
                JsonObject content = jsonObject.getAsJsonObject("content");
                if (content!=null){
                    String address = content.get("address").toString();
                    return address.replaceAll("[省市\"]","");
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
